/* --------------------------- (C) COPYRIGHT 2021 Fortiortech ShenZhen -----------------------------
    File Name      : SLEEP.c
    Author         : Fortiortech  Appliction Team--leo
    Version        : V1.0
    Date           : 2021-12-20
    Description    : This file contains sleep function used for Motor Control.
----------------------------------------------------------------------------------------------------  
                                       All Rights Reserved
------------------------------------------------------------------------------------------------- */
#include <MyProject.h>

/* -------------------------------------------------------------------------------------------------
    Function Name  : Sleepmode_Init
    Description    : 外部中断睡眠引脚设置
    Date           : 2021-12-20
    Parameter      : None
------------------------------------------------------------------------------------------------- */
void Sleepmode_Init(void)
{
    ClrBit(P1_OE, P11);                     // config P11 as input
    ClrBit(P1_PU, P11);                     // diasable P11 Pull Up
    ClrBit(P1_IF, P11);                     // clear P11 interrupt flag
    ClrBit(P1_IE, P11);                     // config P11 as the source of EXTI1
    IT11 = 1;
    IT10 = 0;                               // 00: posedge mode interrupt，01: negedge mode interrupt，1x: edge-change mode interrupt

	SetBit(IP0 , PX11);
    SetBit(IP0 , PX10); 	                // 中断优先级别0，中断优先级最高
    EX1 = 1;                                // 使能外部中断1, P11位外部中断输入硬件
    EA = 1;                                 // 使能全局中断
}



/* -------------------------------------------------------------------------------------------------
    Function Name  : Sleepmode
    Description    : 进入睡眠模式
    Date           : 2021-12-20
    Parameter      : None
------------------------------------------------------------------------------------------------- */
void Sleepmode(void)
{
    SleepSet.SleepDelayCout++;
    
    if (SleepSet.SleepDelayCout >= 6000) //最大65530，若要再大，需改数据类型
    {
        MotorControl.TargetValue = 0;
        MOE     = 0;
		
		/******睡眠模式初始化**********/
	    Sleepmode_Init();
		
        ClrBit(DRV_CR, FOCEN);  //关闭FOC
		ClrBit(ADC_CR,ADCEN); 
		ClrBit(CCFG1, WDT_EN);  //关闭WDT
		
		//关闭运放
		ClrBit(AMP_CR0 , AMP0EN);        //AMP0 Enable
        ClrBit(AMP_CR0 , AMP1EN);        //AMP1 Enable
        ClrBit(AMP_CR0 , AMP2EN);        //AMP2 Enable 

		//关闭比较器
		ClrBit(CMP_CR1 , CMP3EN);   //CMP3 Enable
		
		//关闭VREF
		SetBit(VREF_VHALF_CR, 0x00); 
		
        SleepSet.SleepDelayCout = 0;
        SleepSet.SleepFlag = 1;
        SetBit(P1_IE, P11);   // config P11 as the source of EXTI1
        SetBit(PCON, STOP);
    }
}
